package com.huc.ribbon.rest.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

@RequestMapping("ribbon")
@RestController
public class RibbonController {

	@Autowired
	private DiscoveryClient discoveryClient;

	@RequestMapping("updateWeight")
	public String updateWeight(String serverId, Integer port, Integer weight) {

		List<ServiceInstance> serverLists = discoveryClient.getInstances(serverId);
		for (ServiceInstance serviceInstance : serverLists) {

			if (serviceInstance.getPort() == port) {
				serviceInstance.getMetadata().put("weight", String.valueOf(weight));
			}
		}

		return JSONObject.toJSONString(serverLists);
	}

}
